package org.example.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.example.domain.beans.JwtParseInfo;
import org.example.domain.dto.AdminLoginDto;
import org.example.domain.dto.TokenDto;
import org.example.domain.model.Result;
import org.example.service.IAdminLoginService;
import org.example.util.FmBackendJwtUtils;
import org.example.util.FmFrontedSignatureStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/admin")
@CrossOrigin("*")
public class AdminLoginController {

    private IAdminLoginService adminLoginService;
    private FmBackendJwtUtils fmBackendJwtUtils;
    private Log log = LogFactory.getLog(AdminLoginController.class);

    public AdminLoginController(IAdminLoginService adminLoginService, FmBackendJwtUtils fmBackendJwtUtils) {
        this.adminLoginService = adminLoginService;
        this.fmBackendJwtUtils = fmBackendJwtUtils;
    }

    @PostMapping("/login")
    public Result adminLogin(@RequestBody AdminLoginDto adminLoginDto){
        log.info(String.format("username:%s,password:%s",adminLoginDto.getUsername(),adminLoginDto.getPassword()));
        return adminLoginService.adminlogin(adminLoginDto);
    }

    @PostMapping("/refresh/token")
    public Result refreshToken(@RequestBody TokenDto tokenDto , HttpServletRequest request, HttpServletResponse response){
        String authorization = request.getHeader("Authorization");
        if(StringUtils.hasText(authorization)&&authorization.startsWith("Bearer ")){
            String access_token = authorization.replace("Bearer ", "");
            JwtParseInfo jwtParseInfo = fmBackendJwtUtils.validateAccessJwt(access_token);
            switch (jwtParseInfo.getSignatureStatus()){
                //如果是过期状态才允许换新的token
                case expired://正常过期状态
                    //验证refresh_token
                    jwtParseInfo = fmBackendJwtUtils.validateRefreshJwt(tokenDto.getRefreshToken());
                    //refresh_token是正常状态
                    if(FmFrontedSignatureStatus.correct==jwtParseInfo.getSignatureStatus()){
                        //创建新的access_token
                        String newAccessToken= fmBackendJwtUtils.createAccessToken(jwtParseInfo.getClaims().getSubject());
                        return Result.buildSuccess(newAccessToken);
                    }else {
                        response.setStatus(401);
                        return null;
                    }
                case correct:
                    return Result.buildSuccess(access_token);
                case tamper:
                    response.setStatus(401);
                    return null;
            }
        }
        return null;
    }
}
